package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.AddressDTO;
import com.hmall.common.dto.ItemDTO;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.ThreadLocal4UserId;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createOrder(RequestParams params) {

        //查询商品
        ItemDTO item = itemClient.getById(params.getItemId());
        //基于商品价格以及购买数量计算商品总价
        long total = item.getPrice() * params.getNum();
        //设置订单总价
        Order order = new Order();
        order.setTotalFee(total);

        order.setPaymentType(params.getPaymentType());
        order.setUserId(ThreadLocal4UserId.getUserId());
        order.setStatus(1);

        //更新数据库
        this.save(order);

        //封装订单信息对象
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setName(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setNum(params.getNum());
        orderDetail.setItemId(item.getId());
        orderDetail.setImage(item.getImage());
        orderDetail.setOrderId(order.getId());
        orderDetailService.save(orderDetail);

        //获取收件地址信息
        Long addressId = params.getAddressId();
        AddressDTO address = userClient.findAddressById(addressId);

        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);
        orderLogistics.setOrderId(order.getId());
        orderLogisticsService.save(orderLogistics);

        //扣减库存
        try {
            itemClient.updateStock(params.getItemId(),params.getNum());
        }catch (Exception e){
            throw new RuntimeException("库存不足！");
        }


        //处理超时信息
        Message message = MessageBuilder
                .withBody(order.getId().toString().getBytes(StandardCharsets.UTF_8))
                .setExpiration("30000")//延迟60秒
                .build();

        //消息Id，封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData(order.getId().toString());

        //发送消息
        rabbitTemplate.convertAndSend("order.topic","order.create",message,correlationData);
        //打印成功日志
        log.info("发送消息成功！");


        return order.getId();
    }
}
